package org.vectrics.recruiter.struts.admin;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

import javax.servlet.jsp.JspException;

import org.vectrics.common.util.DateSync;
import org.vectrics.common.util.StringUtils;
import org.vectrics.employee.Employee;
import org.vectrics.hibernate.ThreadProperties;
import org.vectrics.provider.CoreServiceLocator;
import org.vectrics.recruiter.RecruitServiceLocator;
import org.vectrics.struts.VectricsActionData;
import org.vectrics.struts.VectricsStrutsAction;
import org.vectrics.user.PersonCommunication;

import com.hexacta.hrs.securitygroups.PermissionNameConverter;
import com.hexacta.hrs.web.struts.actions.security.PermissionChecker;

public class ShowPersonPhoneCallAction extends VectricsStrutsAction {
	static final long serialVersionUID = 234623400324324L;

	private boolean isEmployee;
	
	@Override
	protected String doExecute(VectricsActionData actionData)
			throws JspException {
		Date startDate = null;
		Date endDate = null;
		String communicationId = actionData.getRequest().getParameter("personCommunicationId");
		String toPersonId = actionData.getRequest().getParameter("personId");
		SimpleDateFormat roundToDateFormat = CoreServiceLocator.getDateFormat().getDateFormatRoundToDay(actionData.getLocale());
		
		PersonPhoneCallForm form = new PersonPhoneCallForm();
		actionData.setRequestForm(form);
		if (StringUtils.isNullOrBlank(communicationId)) {
			log.debug("New communication");
			startDate = DateSync.getCurrentTime();
			form.setStartDate(roundToDateFormat.format(startDate));
			form.setMinutes("10");
			form.setMethodCode("phone");
			form.setFromPersonId(ThreadProperties.getPerson().getId().toString());
			if (StringUtils.isNullOrBlank(toPersonId) == false) {
				form.setToPersonId(toPersonId);
			}

		} else {
			log.debug("Existing communication, find data information and populate action form");
			PersonCommunication personCommunication = CoreServiceLocator.getPersonService().findPersonCommunication(new Long(communicationId));
			startDate = personCommunication.getDateStart();
			endDate = personCommunication.getDateEnd();
			form.setEncounterStatusCode(personCommunication.getEncounterStatus().getCode());
			form.setMethodCode(personCommunication.getMethod().getPersonCommunicationMethodType().getCode());
			form.setNotes(personCommunication.getNotes());

			if (personCommunication.getDateEnd() != null) { 
				long millis = personCommunication.getDateEnd().getTime() - personCommunication.getDateStart().getTime();
				long minutesEllapsed = millis / (1000 * 60);
				form.setMinutes("" + minutesEllapsed);
				log.info("Minutes ellapsed: " + minutesEllapsed);
			}
			
			if (personCommunication.getLeadPerson() != null) {
				form.setFromPersonId(personCommunication.getLeadPerson().getId().toString());
			}
			
			if (personCommunication.getPerson() != null) {
				form.setToPersonId(personCommunication.getPerson().getId().toString());
			}
		}
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(startDate);
		int hour = calendar.get(Calendar.HOUR);
		int minute = calendar.get(Calendar.MINUTE);
		int amPm = calendar.get(Calendar.AM_PM);
		if ((hour == 0) && (amPm > 0)) {
			hour = 12;
		}
		log.info("Hour = " + hour);
		log.info("Minute = " + minute);
		form.setStartHour("" + hour);
		form.setStartMinute("" + minute);
		log.info("AM_PM = " + amPm);
		
		boolean pm = (amPm > 0);

		log.info("PM = " + pm);
		form.setStartHour("" + hour);
		form.setStartMinute("" + minute);
		if (pm) {
			form.setStartAmPm("pm");
		} else {
			form.setStartAmPm("am");
		}
		form.setStartDate(roundToDateFormat.format(startDate));
		
		String personId = actionData.getRequest().getParameter("personId");
		if (personId == null) {
            personId = actionData.getRequest().getParameter("userId");
        }
        if (personId != null) {
            isEmployee = isEmployee(actionData);
        }
		
		return "success";
	}
	
	 
	 protected Boolean isEmployee(VectricsActionData actionData) {
	        String userId = actionData.getRequest().getParameter("userId");

	        if ((userId == null) || (userId.trim().length() == 0)) {
	            userId = (String) actionData.getRequest().getAttribute("userId");
	        }
	        if ((userId == null) || (userId.trim().length() == 0)) {
	            userId = (String) actionData.getRequest().getSession().getAttribute("userId");
	        }
	        if ((userId == null) || (userId.trim().length() == 0)) {
	            userId = actionData.getRequest().getParameter("id");
	        }
	        if ((userId == null) || (userId.trim().length() == 0)) {
	            userId = actionData.getRequest().getParameter("personId");
	        }
	        if ((userId == null) || (userId.trim().length() == 0)) {
	            userId = (String) actionData.getRequest().getAttribute("personId");
	        }
	        if ((userId != null) && (userId.equals("current"))) {
	            userId = ThreadProperties.getPerson().getId().toString();
	        }
	        String personId = userId;
	        if ((userId == null) || (userId.trim().length() == 0)) {
	            throw new RuntimeException("User ID is blank or null");
	        }

	        String companyId = ThreadProperties.getDomain().getPrimaryCompany().getId().toString();

	        // Busco el empleado de la compania.
	        Employee employee = RecruitServiceLocator.getCompanyService().findEmployee(new Long(personId),
	                new Long(companyId));
	        return (employee != null);
	    }


	public void setIsEmployee(boolean isEmployee) {
		this.isEmployee = isEmployee;
	}


	public boolean getIsEmployee() {
		return isEmployee;
	}

}
